﻿<?php
class Model_Store extends Zend_Db_Table_Abstract{
	protected $db;
	public function __construct() {
		$this->db = Zend_Registry::get ( "db" );
	}
	
	public function getItems($options) {
		$table = '`store`';
		$result = array ();
		$query = $this->db->query ( "SELECT COUNT(*) AS Total FROM $table" );
		$row = $query->fetchAll ();
		$result ["total"] = $row [0] ['Total'];	
		foreach($options as $key => $value) {
			$$key = trim($value);
		}
		$cond = '1=1';
		if($kw) {
			$cond .= ' and `description` like \'%'.mysql_escape_string($kw).'%\'';
		}
		
		if($d) {
			$ds = explode('/', $d);
			if(strlen($ds[0]) == 1) $ds[0] = '0' . $ds[0];
			if(strlen($ds[1]) == 1) $ds[1] = '0' . $ds[1];
			$d = $ds[2]. '-' . $ds[0] . '-' . $ds[1];
			$cond .= " and `created` like '%".$d."%'";
		}
		
		$query = $this->db->query ( "SELECT *  FROM $table WHERE $cond order by  $sort $order LIMIT $offset, $rows" );
		$result ['rows'] = $query->fetchAll ();
		
		return $result;
	}
	
	public function create($data) {
		$items = $data['items'];
		unset($data['items']);
		$this->db->insert('store', $data);
		$id = $this->db->lastInsertId();
		$names = array();
		$table = new Model_Table();
		foreach($items as $item) {
			$item['storeId'] = $id;
			$this->db->insert('storeProduct', $item);
			$names[] = $item['productName'];
			$product = $table->select('catalog', $item['productId']);
			$this->db->update('catalog', array('quantity' => ($product['quantity'] + $item['quantity'])), 'id=' . $item['productId']);
		}
		$description = implode(',', $names);
		$dates = array_unique($dates);
		$this->db->update('store', array('description' => $description), 'id='. $id);
	}
	
	public function update($data) {
		$items = $data['items'];
		$id = $data['id'];
		unset($data['items']);
		unset($data['id']);
		$this->db->update('store', $data, 'id=' . $id);
		
		$this->clearItems($id);
		$names = array();
		foreach($items as $item) {
			$item['storeId'] = $id;
			$this->db->insert('storeProduct', $item);
			$names[] = $item['productName'];
		}
		$description = implode(',', $names);
		$this->db->update('store', array('description' => $description), 'id='. $id);
	}
	
	public function load($id) {
		$order = $this->db->query('select * from `store` where id=' . $id)->fetchAll();
		if($order) $order = $order[0];
		$order['items'] = $this->db->query('select * from storeProduct where storeId=' . $id . ' order by id asc')->fetchAll();
		return $order;
	}
	
	public function clearItems($id){
		return $this->db->delete('storeProduct', 'storeId=' . $id);
	}
	
	public function delete($id) {
		$this->db->delete('store', 'id=' . $id);
		$this->clearItems($id);
		
	}
}